package com.wdhcr.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/*
 * @description: jwt身份认证工具类
 * @author: wdhcr
 * @dateTime: 2020/3/18 15:40
 */
@Component
public class JwtUtil {
    /*
     * @description: 签名私钥
     */
    @Value("${jwt.key}")
    private String key;
    /*
     * @description: 签名失效时间
     */
    @Value("${jwt.timeout}")
    private long ttl;

    /*
     * @description: 根据参数信息生成token字符串
     * @params: [id, openid]
     * @return: java.lang.String
     * @author: wdhcr
     * @dateTime: 2020/3/18 15:49
     */
    public String getToken(long id, String openid) {
        //设置失效时间
        long now = System.currentTimeMillis();
        long exp = System.currentTimeMillis() + ttl;
        //创建token
        String token = Jwts.builder()
                .setId(id + "")
                .setSubject(openid)
                .setIssuedAt(new Date(now))
                //设置失效时间
                .setExpiration(new Date(exp))
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
        return token;
    }

    /*
     * @description: 根据token字符串解析出来claims对象
     * @params: [token]
     * @return: io.jsonwebtoken.Claims
     * @author: wdhcr
     * @dateTime: 2020/3/18 15:51
     */
    public Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    }

    public static void main(String[] args) {

        Jwts.parser().setSigningKey("wdhcr").parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoib29SaXF3MC1zdEdlT29qcUJuNFJLMm1UY0docyIsImlhdCI6MTU4ODg1MzQzOSwiZXhwIjoxNTg4ODUzNDQ2fQ._EQgrI0Vbf6rCGQzv3S7uk3yLDZ6w-Y8yjfYPzT3t7k").getBody();
    }
}
